from typing import List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from app.config.database_config import PgManager
from app.models.flight import FlightStatus
from app.schemas.flight import FlightCreate, FlightUpdate, FlightResponse
from app.services.flight_service import FlightService

router = APIRouter(prefix="/flights", tags=["flights"])

def get_flight_service(db: Session = Depends(PgManager.get_db_static)) -> FlightService:
    return FlightService(db)

@router.get("/search", response_model=List[FlightResponse])
def search_flights(
        departure_city: Optional[str] = Query(None, description="出发城市"),
        arrival_city: Optional[str] = Query(None, description="到达城市"),
        departure_date: Optional[str] = Query(None, description="出发日期 (YYYY-MM-DD格式)"),
        airline: Optional[str] = Query(None, description="航空公司"),
        skip: int = Query(0, ge=0, description="跳过的记录数"),
        limit: int = Query(100, ge=1, le=1000, description="返回的记录数"),
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    航班查询：根据出发地、目的地、日期等条件查询航班
    """
    flights = flight_service.get_flights(
        departure_city=departure_city,
        arrival_city=arrival_city,
        departure_date=departure_date,
        airline=airline,
        skip=skip,
        limit=limit
    )
    return flights


@router.get("/{flight_id}", response_model=FlightResponse)
def get_flight_details(
        flight_id: int,
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    航班详情：查看航班详细信息
    """
    flight = flight_service.get_flight_by_id(flight_id)
    if not flight:
        raise HTTPException(status_code=404, detail="航班未找到")
    return flight


@router.get("/number/{flight_number}", response_model=FlightResponse)
def get_flight_by_number(
        flight_number: str,
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    根据航班号查询航班详情
    """
    flight = flight_service.get_flight_by_number(flight_number)
    if not flight:
        raise HTTPException(status_code=404, detail="航班未找到")
    return flight


@router.post("/", response_model=FlightResponse)
def create_flight(
        flight: FlightCreate,
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    创建新航班（管理员功能）
    """
    existing_flight = flight_service.get_flight_by_number(flight.flight_number)
    if existing_flight:
        raise HTTPException(status_code=400, detail="航班号已存在")

    return flight_service.create_flight(flight)


@router.get("/", response_model=List[FlightResponse])
def get_flights_list(
        skip: int = Query(0, ge=0, description="跳过的记录数"),
        limit: int = Query(100, ge=1, le=1000, description="返回的记录数"),
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    获取航班列表：支持分页查询所有航班
    """
    flights = flight_service.get_flights(skip=skip, limit=limit)
    return flights


@router.put("/{flight_id}", response_model=FlightResponse)
def update_flight(
        flight_id: int,
        flight_update: FlightUpdate,
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    更新航班信息（管理员功能）
    """
    flight = flight_service.update_flight(flight_id, flight_update)
    if not flight:
        raise HTTPException(status_code=404, detail="航班未找到")
    return flight


@router.patch("/{flight_id}/status", response_model=FlightResponse)
def update_flight_status(
        flight_id: int,
        status: FlightStatus,
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    航班状态更新：更新航班状态（延误、取消等）
    """
    flight = flight_service.update_flight_status(flight_id, status)
    if not flight:
        raise HTTPException(status_code=404, detail="航班未找到")
    return flight


@router.delete("/{flight_id}")
def delete_flight(
        flight_id: int,
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    删除航班（管理员功能）
    """
    success = flight_service.delete_flight(flight_id)
    if not success:
        raise HTTPException(status_code=404, detail="航班未找到")
    return {"message": "航班删除成功"}


@router.get("/{flight_id}/availability")
def check_flight_availability(
        flight_id: int,
        requested_seats: int = Query(1, ge=1, description="请求的座位数"),
        flight_service: FlightService = Depends(get_flight_service)
):
    """
    检查航班座位可用性
    """
    available = flight_service.check_availability(flight_id, requested_seats)
    if not available:
        flight = flight_service.get_flight_by_id(flight_id)
        if not flight:
            raise HTTPException(status_code=404, detail="航班未找到")
        raise HTTPException(status_code=400, detail="座位不足")

    return {"available": True, "requested_seats": requested_seats}
